<template>
  <view class="contianer-sale">
    <!-- 搜索会员卡(手机摄像头扫描) -->
    <view class="container-card">
      <u-form :model="cardnumberform" ref="uForm">
        <div class="cardnumber-contianer">
          <u-form-item class="card-input"
            ><u-input
              border="true"
              v-model="cardnumberform.cardnumber"
              placeholder="请输入您的会员卡号/手机号"
          /></u-form-item>
          <u-button @click="searchCardnumber" type="primary"
            >查询会员卡</u-button
          >
        </div>
      </u-form>
      <view>
        <!-- 会员卡列表 -->
        <view v-if="cardlist.length > 0" class="cardlist">
          <view
            @click="handleClick(index, item)"
            :class="[{ 'card-item-active': index == activeIndex }]"
            class="card-item"
            v-for="(item, index) in cardlist"
            :key="index"
          >
            <view class="subitem">
              <view>手机号:</view>
              <view>{{ item.mobile }}</view>
            </view>
            <view class="subitem"
              ><view>标题:</view> <view>{{ item.titile }}</view></view
            >
            <view class="subitem"
              ><view>卡级别:</view> <view>{{ item.astrict_text }}</view></view
            >
            <view class="subitem"
              ><view>卡类型:</view> <view>{{ item.type_text }}</view></view
            >
            <view class="subitem"
              ><view>到期时间:</view> <view>{{ item.endtime_text }}</view></view
            >
          </view>
        </view>
        <view v-else
          ><u-empty style="text-align: center" text="暂无会员卡数据"></u-empty
        ></view>
      </view>
    </view>

    <!-- 商品扫码(条形码) -->
    <view>
      <u-form :model="goodsnumberform" ref="uForm">
        <div class="cardnumber-contianer">
          <u-form-item class="card-input"
            ><u-input
              border="true"
              v-model="goodsnumberform.goodsnumber"
              placeholder="请扫描条形码"
          /></u-form-item>

          <u-button @click="searchGood" type="primary">查询商品</u-button>
        </div>
      </u-form>
      <!-- 真实扫码 -->
      <!-- <view>
        <u-button @click="saoMa()" type="primary">扫码查询</u-button>
      </view> -->
      <!-- 商品列表 -->
      <view class="goodslist-container">
        <u-table>
          <u-tr class="u-tr">
            <u-th class="u-th">名称</u-th>
            <u-th class="u-th">规格</u-th>
            <u-th class="u-th">单价</u-th>
            <u-th class="u-th">会员价</u-th>
            <u-th class="u-th">数量</u-th>
            <u-th class="u-th">操作</u-th>
          </u-tr>

          <u-tr
            class="u-tr"
            v-for="(item, index) in goodsitemlist"
            :key="index"
          >
            <u-td class="u-td">{{ item.goodsname }}</u-td>
            <u-td class="u-td">{{ item.goodsvalue }}</u-td>
            <u-td class="u-td">{{ item.goodssingleprice }}</u-td>
            <u-td class="u-td">{{ item.goodsvipprice }}</u-td>
            <u-td class="u-td">{{ item.goods }}</u-td>
            <u-td class="u-td">
              <button @click="handleDelete(index, item)" class="del-btn">
                删除
              </button>
            </u-td>
          </u-tr>
        </u-table>
      </view>
    </view>
    <!-- 真实扫码 -->
    <!-- <view>
      <u-button @click="saoMa()" type="primary">扫码查询</u-button>
    </view> -->

    <!-- 折扣和抹零盒子 -->
    <view class="zhekou-box">
      <!-- 折扣 -->
      <view class="zhekoubox-item">
        <view style="width: 30%">折扣:</view>
        <u-form-item style="width: 40%">
          <u-input v-model="zhekou" border="true" placeholder="请输入" />
        </u-form-item>
      </view>
      <!-- 抹零 -->
      <view class="zhekoubox-item itemself">
        <view style="width: 30%">抹零:</view>
        <u-form-item style="width: 40%"
          ><u-input v-model="clearzero" border="true" placeholder="请输入"
        /></u-form-item>
      </view>
    </view>
    <!-- 结算方式 -->
    <view class="jiesuan">
      <view class="tejia">
        <view style="margin-top: -20rpx; margin-right: 20rpx; color: #000"
          >特价:</view
        >
        <u-form-item
          ><u-switch @change="change()" v-model="switchVal"></u-switch
        ></u-form-item>
      </view>
      <view class="h">
        <u-radio-group v-model="payvalue" @change="radioGroupChange">
          <u-radio
            :icon-size="40"
            v-for="(item, index) in list"
            :key="index"
            :name="item.value"
            :disabled="item.disabled"
          >
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </view>
      <!-- 立即支付 -->
      <view class="pay-btn">
        <view class="pay-totalprice">
          <!-- <text>商品总数:{{ countNum }}</text> -->
          <text class="pay-l">实际支付:</text>
          <text class="pay-r">{{ price.toFixed(2) }}元</text>
        </view>
        <u-button
          @click="handlePay()"
          type="primary"
          shape="circle"
          size="medium"
          >立即支付</u-button
        >
      </view>
    </view>
    <u-mask :show="show" @click="show = false">
      <view class="warp">
        <view class="rect">
          <img :src="erweimaurl" alt="" />
        </view>
      </view>
    </u-mask>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 会员卡
      cardnumberform: {
        cardnumber: "",
      },
      // 会员卡列表
      cardlist: [
        // {
        //   tel: "18443128596",
        //   title: "这是标题",
        //   grade: "199",
        //   cardtype: "打折卡",
        //   time: "2021-02-01",
        // },
      ],
      // 会员卡折扣
      // carddiscount: 0,
      //   搜索商品
      goodsnumberform: {
        goodsnumber: "",
      },
      // 商品最终列表
      goodsitemlist: [],
      // 商品列表
      goodslist: [],
      // 商品规格
      goodsvaluelist: [],
      goodsobj: {
        // 商品名称
        goodsname: "",
        // 商品规格
        goodsvalue: "",
        // 商品单价
        goodssingleprice: "",
        // 商品会员价
        goodsvipprice: "",
        // 商品数量
        goods: 1,
        id: 0,
      },
      // 商品id数组
      goodsidlist: [],

      //   特价
      switchVal: false,
      // kaiguan: false,
      //   折扣
      zhekou: "1",
      // 抹零
      clearzero: 0,
      //   卡片当前项
      iscarditemActive: "",
      // 结算方式
      list: [
        {
          value: "xj",
          name: "现金支付",
          disabled: false,
        },
        {
          value: "wx",
          name: "微信支付",
          disabled: false,
        },
        {
          value: "zfb",
          name: "支付宝支付",
          disabled: false,
        },
      ],
      // u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中.

      payvalue: "xj",
      // 卡片选中项
      activeIndex: -1,
      // 卡的折扣核价
      price: 0,
      // 出售类型
      type: "1",
      // 租赁类型
      // 会员卡的id
      cardid: 0,
      // 订单号
      dingdanhao: "",
      // 图片
      erweimaurl: "",
      show: false,
      timer: null,
    };
  },
  computed: {
    // countNum() {
    //   // 计算商品总数量(回调函数第一个参数是方法中第二个参数的值)
    //   return this.goodsitemlist.reduce((prev, next) => {
    //     return prev + next.goods - 0;
    //   }, 0);
    // },
    // 计算商品总价
    countPrice() {
      console.log(this.switchVal);
      // 计算单价
      var a = this.goodsitemlist.reduce((prev, next) => {
        return prev + (next.goods - 0) * next.goodssingleprice;
      }, 0);
      // 计算会员价
      var b = this.goodsitemlist.reduce((prev, next) => {
        return prev + (next.goods - 0) * next.goodsvipprice;
      }, 0);
      console.log(b);
      // 不等于-1就是点击了会员卡
      // 等于-1没点击
      if (this.activeIndex == -1 || this.switchVal) {
        console.log(this.price);
        // 折扣不是1且不是0 就乘
        if (this.zhekou == "") {
          this.price = a;
        } else if (this.zhekou !== 1 && this.zhekou !== 0 && this.zhekou < 2) {
          this.price = a * (this.zhekou * 1);
        }
        // 抹零
        // 抹零不能超过实际支付
        // 抹零价格大于price 提示

        if (this.clearzero * 1 > this.price) {
          uni.showToast({
            title: "抹零太大了",
            icon: "none",
            duration: 2000,
          });
        } else {
          this.price = this.price - this.clearzero * 1;
        }
      } else if (this.activeIndex !== -1) {
        // 点击了会员卡且特价也开了走单价
        // // 折扣不是1且不是0 就乘
        if (this.zhekou == "") {
          this.price = b;
        } else if (this.zhekou !== 1 && this.zhekou !== 0 && this.zhekou < 2) {
          this.price = b * (this.zhekou * 1);
        }
        // 抹零
        // 抹零不能超过实际支付
        // 抹零价格大于price 提示

        if (this.clearzero * 1 > this.price) {
          uni.showToast({
            title: "抹零太大了",
            icon: "none",
            duration: 2000,
          });
        } else {
          this.price = this.price - this.clearzero * 1;
        }
      } else {
      }
    },
  },
  methods: {
    // 支付
    handlePay() {
      console.log(this.payvalue);
      if (this.payvalue == "xj") {
        if (this.price < 0) {
          this.$refs.uToast.show({
            title: "亲,不能倒贴哦!",
            type: "default",
          });
        } else {
          uni.request({
            url: "http://gxyckf.1qit.com/api/admin.cashier/Cashier_pay",
            method: "POST",
            data: {
              // 请求参数
              goodsSkuIds: this.goodsidlist,
              tejia: this.switchVal,
              type: this.type,
              cardid: this.cardid,
              discount: this.zhekou,
              zero: this.clearzero,
              pay_type: this.payvalue,
            },
            header: {
              // token: "adminb0e5df2a-78ae-48e0-8614-1c7ee2a53173",
              token: uni.getStorageSync("token"),
            },
            success: (res) => {
              if (res.data.code == 1) {
                console.log(res.data.data);
                // 订单号
                this.dingdanhao = res.data.data;
                console.log(this.payvalue);
                // 现金支付
                uni.request({
                  url: "http://gxyckf.1qit.com/api/admin.cashier/pay_online",
                  method: "POST",
                  data: {
                    order_id: res.data.data,
                  },
                  header: {
                    // token: "adminb0e5df2a-78ae-48e0-8614-1c7ee2a53173",
                    token: uni.getStorageSync("token"),
                  },
                  success: (res) => {
                    console.log(res.data);

                    uni.showModal({
                      title: "现金支付",
                      content: res.data.msg,
                      success: function (res) {
                        if (res.confirm) {
                          console.log("用户点击确定");
                          uni.redirectTo({
                            url: "/pages/cashiersale/cashiersale",
                          });
                        } else if (res.cancel) {
                          console.log("用户点击取消");
                          // uni.redirectTo({
                          //   url: "/pages/cashiersale/cashiersale",
                          // });
                        }
                      },
                    });
                  },
                });
              } else if (res.data.code == 0) {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000,
                });
              }
            },
          });
        }
      } else if (this.payvalue == "zfb") {
        if (this.price <= 0) {
          this.$refs.uToast.show({
            title: "支付金额需大于0.01元",
            type: "default",
          });
        } else {
          uni.request({
            url: "http://gxyckf.1qit.com/api/admin.cashier/Cashier_pay",
            method: "POST",
            data: {
              // 请求参数
              goodsSkuIds: this.goodsidlist,
              tejia: this.switchVal,
              type: this.type,
              cardid: this.cardid,
              discount: this.zhekou,
              zero: this.clearzero,
              pay_type: this.payvalue,
            },
            header: {
              // token: "adminb0e5df2a-78ae-48e0-8614-1c7ee2a53173",
              token: uni.getStorageSync("token"),
            },
            success: (res) => {
              if (res.data.code == 1) {
                console.log(res.data.data);
                // 订单号
                this.dingdanhao = res.data.data;
                console.log(this.payvalue);
                // 支付宝
                uni.request({
                  url: "http://gxyckf.1qit.com/api/admin.cashier/pay_online",
                  method: "POST",
                  data: {
                    order_id: res.data.data,
                  },
                  responseType: "arraybuffer",
                  header: {
                    // token: "adminb0e5df2a-78ae-48e0-8614-1c7ee2a53173",
                    token: uni.getStorageSync("token"),
                  },
                  success: (res) => {
                    console.log(res.data);
                    this.show = true;

                    let url =
                      "data:image/png;base64," +
                      uni.arrayBufferToBase64(res.data);
                    console.log(url);
                    this.erweimaurl = url;

                    this.timer = setInterval(() => {
                      this.handlePayResult();
                    }, 1500);
                  },
                });
              } else if (res.data.code == 0) {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000,
                });
              }
            },
          });
        }
      } else if (this.payvalue == "wx") {
        console.log("还没有");
      }
    },
    // 查询支付结果
    handlePayResult() {
      uni.request({
        url: "http://gxyckf.1qit.com/api/admin.cashier/selectPay",
        data: {
          order_id: this.dingdanhao,
        },
        header: {
          token: uni.getStorageSync("token"),
        },
        success: (res) => {
          console.log(res);
          console.log(res.data);
          if (res.data.code == 1) {
            console.log("支付成功");
            uni.showToast({
              title: "支付成功",
              icon: "success",
              duration: 2000,
            });

            this.show = false;

            clearInterval(this.timer);
          }
        },
      });
    },
    // 查询会员卡
    searchCardnumber() {
      console.log("----查询会员卡----");

      uni.request({
        url: "http://gxyckf.1qit.com/api/admin.cashier/searchCardByMobile",
        method: "POST",
        data: {
          // 手机号/会员卡号
          mobile: this.cardnumberform.cardnumber,
        },
        header: {
          // token: "adminb0e5df2a-78ae-48e0-8614-1c7ee2a53173",
          token: uni.getStorageSync("token"),
        },
        success: (res) => {
          console.log(res.data.data);

          if (res.data.code !== 1) {
            this.cardlist = [];
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
            this.cardnumberform.cardnumber = "";
          } else {
            this.cardnumberform.cardnumber = "";
            this.cardlist = JSON.parse(JSON.stringify(res.data.data));
            this.cardlist;
          }
        },
      });
    },
    // 查询商品列表
    searchGood() {
      console.log("----查询商品---");
      uni.request({
        url: "http://gxyckf.1qit.com/api/admin.cashier/searchGoodsByCode",
        method: "POST",
        data: {
          // 商品id
          sku_id: this.goodsnumberform.goodsnumber,
          // sku_id: 123456789019,
        },
        header: {
          // token: "adminb0e5df2a-78ae-48e0-8614-1c7ee2a53173",
          token: uni.getStorageSync("token"),
        },
        success: (res) => {
          console.log("查询商品");
          console.log(res.data);
          if (res.data.code !== 1) {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
          } else {
            this.goodsnumberform.goodsnumber = "";

            this.goodslist = res.data.data.goods;
            this.goodsvaluelist = res.data.data.goods_sku_value;

            // 取商品名称
            this.goodsobj.goodsname = this.goodslist.title;
            // 单价
            this.goodsobj.goodssingleprice = this.goodslist.price;
            // 取会员价
            this.goodsobj.goodsvipprice = this.goodslist.vip_price;

            // 规格
            this.goodsobj.goodsvalue = this.goodsvaluelist.value;
            // 商品id
            this.goodsobj.id = res.data.data.id;
            this.goodsitemlist.push(JSON.parse(JSON.stringify(this.goodsobj)));
            this.goodsidlist = this.goodsitemlist.map((item) => {
              return item.id;
            });
            console.log(this.goodsidlist);
          }
        },
      });
    },
    // 开关事件
    change(status) {
      console.log(status);
      // console.log(switchVal);
      this.switchVal = status;
      console.log(this.switchVal);
    },
    // 点击卡片事件
    handleClick(index, item) {
      console.log("-----点击卡片了------");
      this.activeIndex = index;

      this.cardid = item.id;

      // console.log(this.carddiscount);
    },
    // 商品删除
    handleDelete(index, item) {
      // console.log(index);
      console.log(item);
      this.goodsitemlist.splice(index, 1);
    },
    // 结算方式

    radioGroupChange(payvalue) {
      console.log(payvalue);
    },
    // 扫码查询
    saoMa() {
      uni.scanCode({
        // success: function (res) {
        //   console.log(JSON.stringify(res.result));
        // },
        scanType: ["barCode"],
        success: function (res) {
          console.log("条码类型：" + res.scanType);
          console.log("条码内容：" + res.result);
        },
      });
    },
  },
};
</script>

<style scoped>
.container-card {
  /* margin-bottom: 40rpx; */
}
.contianer-sale {
  background: #fff;
  padding: 0px 40rpx;
}
.dflex-btn {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.subitem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}
.cardlist {
  background: #fff;
  padding: 40rpx 0;
  overflow-y: auto;
  height: 260rpx;
}
.card-item {
  color: #fff;
  font-size: 30rpx;
  font-weight: 600;
  background: #2979ff;
  opacity: 0.4;
  padding: 10rpx;
  box-shadow: 0 0 30rpx #ddd;

  border-radius: 20rpx;
  margin-bottom: 20rpx;
}
.card-item-active {
  background: #2979ff;
  opacity: 1;
}

.goodslist-container {
  overflow-y: auto;
  height: 260rpx;
}
.u-th {
  width: 184rpx;
}
.u-td {
  width: 184rpx;
}
.del-btn {
  /* width: ; */
  font-size: 20rpx;
  outline: none;
  background: #2979ff;
  color: #fff;
}

.cardnumber-contianer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-input {
  flex: 1;
  margin-right: 5rpx;
}
.jiesuan {
  overflow: hidden;
  width: 100%;
  position: fixed;
  box-shadow: 0 0 20rpx #ccc;
  background: #fff !important;
  padding-top: 10rpx;
  bottom: 0;
  right: 0;
  z-index: 9999;
}
.h {
  display: flex;
  justify-content: flex-end;
}
.pay-btn {
  text-align: right;
  justify-content: flex-end;
  padding-top: 30rpx;
  display: flex;
  align-items: center;
}
.pay-totalprice {
  font-size: 32rpx;
  font-weight: 600;
}
.pay-l {
  margin-right: 20rpx;
}
.pay-r {
  margin-right: 20rpx;
}
.tejia {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.zhekou-box {
  /* z-index: 999999; */
  display: flex;
  align-items: center;
  position: fixed;
  bottom: 290rpx;
}
.zhekoubox-item {
  display: flex;
  align-items: center;
}
.warp {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.rect {
  width: 320rpx;
  height: 320rpx;
  background-color: #fff;
}
img {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
